axios.defaults.baseURL='http://ajax-base-api-t.itheima.net'
const tbody = document.querySelector('#tb');
//界面初始化
async function renderData() {
    const {data:res} = await axios.get('/api/getbooks')
    const html = res.data.map((item) => {
        const {id, bookname,author,publisher} = item
        return `
        <tr>
        <td>${id}</td>
        <td>${bookname}</td>
        <td>${author}</td>
        <td>${publisher}</td>
        <td><a href="#" data-id=${id}>删除</a></td>
        </tr>`
      }).join('')
      tbody.innerHTML = html
    }


renderData()

const searchBtn = document.querySelector('#btnSearch');
const addBtn = document.querySelector('#btnAdd');
const form =document.querySelector('#bookForm');
//增
addBtn.addEventListener('click',async function (e) {
    e.preventDefault()
    try {
        const data = serialize(form,{hash:true})
        const {data:res} = await axios.post('/api/addbook',data)
        alert(res.msg)
        if(res.status!== 201) {
            return 
          }
        this.reset()
        renderData()
        
    } catch (error) {
        console.log(error);
    }
       
})
//删
tbody.addEventListener('click',async function (e) {
    if (e.target.tagName === 'A') {
        const id = e.target.dataset.id
        const {data:res} = await axios.get('/api/delbook',{ params:{id} })
        alert(res.msg)
        renderData()
    }
});
